<template>
	<a-tabs v-model:activeKey="activeTab" class="invoice-tabs" @change="onTabChange">
		<a-tab-pane key="1" tab="可开发票">
			<template v-if="pageStatusValue === 0">
				<vxe-grid
					:data="tableData"
					v-bind="billTableOption"
					ref="xTable1"
					:loading="loadings.detail"
					@checkbox-all="selectAllChangeEvent1"
					@checkbox-change="selectChangeEvent1">
					<template #status="{row}">
						<template v-if="row.billStatus === 1">
							<a-tag v-if="row.notOccurredMoney >= 0" color="processing">待收款</a-tag>
							<a-tag v-else color="error">待付款</a-tag>
							<small v-if="row.overdueDays" v-color="{color: 'danger'}">逾期{{ row.overdueDays }}天</small>
						</template>
						<template v-else-if="row.billStatus === 2">
							<a-tag color="success">已结清</a-tag>
						</template>
						<template v-else-if="row.billStatus === 9">
							<a-tag color="default">已作废</a-tag>
						</template>
					</template>

					<template #detail="{row}">
						<vxe-table
							:data="row.billDetailDTOList"
							v-bind="billChildOption"
							:show-header="false"
							@checkbox-change="selectChangeEvent2">
							<vxe-column type="checkbox" width="30" />
							<vxe-column min-width="100" align="center" field="feeSubjectValue" />
							<vxe-column min-width="100" align="center">
								<template #default="{row}">应收: {{ row.originalMoney.toLocaleString() }}元</template>
							</vxe-column>
							<vxe-column min-width="100" align="center">
								<template #default="{row}">已收: {{ row.occurredMoney.toLocaleString() }}元</template>
							</vxe-column>
							<vxe-column min-width="100" align="center">
								<template #default="{row}">待收: {{ row.notOccurredMoney.toLocaleString() }}元</template>
							</vxe-column>
							<vxe-column min-width="100" align="center">
								<template #default="{row}">已开票: {{ row.hasInvoicingMoney.toLocaleString() }}元</template>
							</vxe-column>
							<vxe-column min-width="100" align="center">
								<template #default="{row}">
									<span style="color: red">可开票: {{ row.invoiceMoney.toLocaleString() }}元</span>
								</template>
							</vxe-column>
							<vxe-column min-width="200" align="center">
								<template #default="{row}">已收时间: {{ row.practicalTime || '暂未收款' }}</template>
							</vxe-column>
							<vxe-column min-width="200" align="center">
								<template #default="{row}">周期:{{ formatDate(row.beginTime) }}至{{ formatDate(row.endTime) }}</template>
							</vxe-column>
							<vxe-column title="操作" width="100" align="center">
								<template #default="{row}">
									<a @click="record(row.id)">开票记录</a>
								</template>
							</vxe-column>
						</vxe-table>
					</template>
					<template #action="{row}">
						<a>明细</a>
					</template>
					<template #bottom>
						<a-space :size="12" class="text-right">
							<a-button
								v-if="hasPermissions(['mk_finance_invoicing_apply_additional_recording'])"
								type="primary"
								@click="submit(2)"
								:disabled="!tableData.filter(e => e.billDetailDTOList.filter(j => j.isDealWith).length).length">
								发票补录
							</a-button>

							<a-button
								v-if="hasPermissions(['mk_finance_invoicing_apply_submit'])"
								type="primary"
								@click="submit(1)"
								:disabled="!tableData.filter(e => e.billDetailDTOList.filter(j => j.isDealWith).length).length">
								申请开票
							</a-button>
						</a-space>
					</template>
				</vxe-grid>
			</template>
			<template v-else>
				<a-result class="default-box">
					<template #title>
						<template v-if="pageStatusValue === 1">
							{{ pageStatus[pageStatusValue].title }}
						</template>
						<template v-else>该“{{ pageStatus[pageStatusValue].name }}”部门{{ pageStatus[pageStatusValue].title }}</template>
					</template>
					<template #subTitle>
						{{ pageStatus[pageStatusValue].content }}
					</template>
					<template #extra>
						<a-button type="primary" @click="switchRouter">{{ pageStatus[pageStatusValue].buttonText }}</a-button>
					</template>
				</a-result>
			</template>
		</a-tab-pane>

		<a-tab-pane key="2" tab="开票历史">
			<invoiceing-history
				v-if="activeTab === '2'"
				searchContainer="#top_search_invoice"
				:query="{id: props.dataSource.id, enterType: props.enterType}" />
		</a-tab-pane>

		<template #rightExtra>
			<div v-if="activeTab === '2'" id="top_search_invoice"></div>
			<search-input v-else v-model:params="searchParams" v-bind="searchOption" />
		</template>
	</a-tabs>

	<!-- 申请开票 and 发票补录 -->
	<apply-invoice-dialog
		v-model:visible="visibles.applyInvoice"
		:billDetailItems="billDetailItems"
		:data-source="props.dataSource"
		:page-type="pageType"
		:dept-id="props.dataDept.deptId"
		@close="
			() => {
				emits('success')
				getFinance()
			}
		" />

	<!-- 开票记录 -->
	<invoicing-records v-model:visible="visibles.records" :id="recordId" @close="getFinance()" />
</template>

<script setup lang="ts">
	import {onMounted, reactive, ref} from 'vue'
	import {VxeGridProps, VxeTableEvents, VxeTableInstance, VxeTableProps} from 'vxe-table'
	// import InvoiceingHistory from '@/components/contract/contract-detail-dialog/invoiceing-history.vue'
	import InvoiceingHistory from '@/pages/finance/invoice-administration/billing-history/index.vue'
	import ApplyInvoiceDialog from '@/components/contract/invoice/apply-invoice.vue'
	import InvoicingRecords from '@/components/contract/invoice/invoicing-records.vue'
	import {useStore} from '@/store/index'
	import invoicing from '@/api/invoicing'
	import {RouteLocationRaw, useRoute, useRouter} from 'vue-router'
	import {SearchProps} from 'yuxin-base/src/types'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import dayjs from 'dayjs'
	import DATE_FORMAT, {formatDate} from 'yuxin-base/src/utils/date'

	const route = useRoute()
	const router = useRouter()

	// 过滤出财务模块路由
	const tabList = route.matched[0].children
		.filter((o: any) => o.name === 'Finance')[0]
		.children?.filter((o: any) => o.name === 'InvoiceAdministration')[0].children

	const hasPermissions = useStore().hasPermissions

	const props = defineProps({
		dataSource: {
			type: Object,
			required: true
		},
		dataDept: {
			type: Object,
			required: true
		},
		enterType: {
			type: Number,
			required: true
		}
	})

	const emits = defineEmits(['update:visible', 'success'])

	const activeTab = ref('1')
	const visibles = reactive({
		applyInvoice: false,
		records: false
	})
	const loadings = reactive({
		detail: false,
		save: false
	})
	const tableData = ref<any[]>([])
	const billDetailItems = ref<any[]>([])
	const recordId = ref<any>(null)
	const pageType = ref<any>(1)

	const pageStatusValue = ref(0)

	const pageStatus: any = reactive({
		1: {
			name: null,
			title: '暂无开票主体',
			content: '暂无可使用的开票主体，请先配置开票主体。',
			buttonText: '配置开票主体',
			key: '开票主体'
		},
		2: {
			name: null,
			title: '暂无开票信息',
			content: '暂无可使用的开票信息，请先配置开票信息。',
			buttonText: '配置开票信息',
			key: '开票信息'
		},
		3: {
			name: null,
			title: '暂无税收信息',
			content: '暂无可使用的税收信息，请先配置税收信息。',
			buttonText: '配置税收信息',
			key: '税率配置'
		},
		4: {
			name: null,
			title: '暂无开票审批',
			content: '暂无可使用的开票审批，请先配置开票审批。',
			buttonText: '配置开票审批',
			key: '审批配置'
		}
	})

	/** 决策设置 */
	const setting = ref(false)

	const searchParams = reactive<any>({
		like: null,
		matchType: null
	})
	// 搜索配置
	const searchOption = reactive<SearchProps>({
		placeholder: '房源地址',
		onSearch() {
			getFinance()
		}
	})

	const xTable1 = ref<VxeTableInstance>()

	const billTableOption = reactive<VxeGridProps>({
		size: 'medium',
		height: 'auto',
		rowConfig: {
			isHover: true
		},
		expandConfig: {
			trigger: 'row',
			showIcon: false
		},
		checkboxConfig: {
			checkField: 'isDealWith',
			checkMethod({row}) {
				// 需要计算二级菜单是否全部被禁用
				if (setting.value) {
					return row.billDetailDTOList.filter(
						e => dayjs().isAfter(dayjs(e.endTime), 'month') && e.occurredMoney && !e.disableInvoice && e.invoiceMoney > 0
					).length
				} else {
					return row.billDetailDTOList.filter(e => !e.disableInvoice && e.invoiceMoney > 0).length
				}

				// return row.billDetailDTOList.filter(e => !e.disableInvoice && e.invoiceMoney > 0).length
			}
		},
		columns: [
			{
				type: 'checkbox',
				width: 30
			},
			{
				type: 'expand',
				field: 'status',
				title: '账单状态',
				width: 100,
				align: 'center',
				slots: {
					default: 'status',
					content: 'detail'
				}
			},
			{
				field: 'houseAddress',
				title: '房源地址',
				minWidth: 240,
				resizable: true
			},
			{
				field: 'billName',
				title: '摘要',
				align: 'center',
				minWidth: 150,
				resizable: true
			},
			{
				title: '账单周期',
				align: 'center',
				width: 200,
				resizable: true,
				formatter({row}) {
					return `${formatDate(row.beginTime)} 至 ${formatDate(row.endTime)}元`
				}
			},
			{
				title: '应收/已收',
				align: 'center',
				minWidth: 120,
				resizable: true,
				formatter({row}) {
					return `${row.totalMoney.toLocaleString()}元/${row.occurredMoney.toLocaleString()}元`
				}
			},
			{
				title: '待收',
				align: 'center',
				minWidth: 120,
				resizable: true,
				formatter({row}) {
					return `${row.notOccurredMoney.toLocaleString()}元`
				}
			},
			{
				title: '应收日期',
				align: 'center',
				minWidth: 120,
				resizable: true,
				formatter({row}) {
					return formatDate(row.predictTime) as string
				}
			},
			{
				title: '操作',
				align: 'center',
				width: 100,
				slots: {
					default: 'action'
				}
			}
		]
	})

	const billChildOption = reactive<VxeTableProps>({
		size: 'medium',
		border: 'inner',
		checkboxConfig: {
			checkField: 'isDealWith',
			checkMethod({row}) {
				// 决策设置 可开发票页面中账单明细的结束日期小于当月的已收款
				if (setting.value) {
					return dayjs().isAfter(dayjs(row.endTime), 'month') && row.occurredMoney && !row.disableInvoice && row.invoiceMoney > 0
				} else {
					return !row.disableInvoice && row.invoiceMoney > 0
				}
			}
		}
	})

	// 申请开票 and 发票补录
	const submit = (type = 1) => {
		// 兼容包租合同入口
		// eslint-disable-next-line vue/no-mutating-props
		props.dataSource.house = {
			deptId: props.dataDept.deptId
		}

		pageType.value = type

		billDetailItems.value = []
		// 过滤已勾选明细
		for (let item of tableData.value) {
			for (const bill of item.billDetailDTOList) {
				if (bill.isDealWith) {
					billDetailItems.value.push(bill)
				}
			}
		}
		billDetailItems.value.forEach(e => {
			e.billDetailId = e.id
			e.price = e.invoiceMoney
			e.feeSubjectName = e.feeSubjectValue
			e.deptId = props.dataDept.deptId

			if (props.dataSource.contractType === 2) {
				props.dataSource.houseRoomDTOList?.forEach(j => {
					if (j.houseBaseId === e.housePid) {
						e.deptId = j.deptId
					}
				})
			}
		})
		console.log('billDetailItems===', billDetailItems.value)

		// 暂时注释
		// if (billDetailItems.value.length > 8) {
		// 	message.warning('所选明细不能超过八条')
		// 	return
		// }

		visibles.applyInvoice = true
	}

	/** 切换路由 */
	const switchRouter = () => {
		// 审批配置
		if (pageStatusValue.value === 4) {
			router.push('/approval/configure')
		} else {
			console.log('🚀 ~ file: invoiceing.vue:249 ~ switchRouter ~ tabList:', tabList)

			router.push(tabList?.filter(e => e.meta?.title === pageStatus[pageStatusValue.value].key)[0].path as RouteLocationRaw)
		}
	}

	// 第一级选中按钮
	const selectChangeEvent1: VxeTableEvents.CheckboxChange = e => {
		let id = e.row.id
		tableData.value.forEach((items: any) => {
			if (items.id === id) {
				items.billDetailDTOList.forEach((items2: any) => {
					items2.isDealWith = false
					// 是否禁止开票
					// if (!items2.disableInvoice && items2.invoiceMoney > 0) {
					// 	items2.isDealWith = e.checked
					// }
					if (setting.value) {
						if (
							dayjs().isAfter(dayjs(items2.endTime), 'month') &&
							items2.occurredMoney &&
							!items2.disableInvoice &&
							items2.invoiceMoney > 0
						) {
							items2.isDealWith = e.checked
						}
					} else {
						if (!items2.disableInvoice && items2.invoiceMoney > 0) {
							items2.isDealWith = e.checked
						}
					}
				})
			}
		})
	}

	// 第二级选中按钮
	const selectChangeEvent2: VxeTableEvents.CheckboxChange = ({checked}) => {
		tableData.value.forEach((items: any, index: any) => {
			let temp: any[] = []
			items.billDetailDTOList.forEach((items2: any) => {
				temp.push(items2.isDealWith)
			})

			temp = temp.filter(e => e == true)

			if (temp.length == items.billDetailDTOList.length) {
				xTable1.value?.setCheckboxRow([items], true)
			} else {
				xTable1.value?.setCheckboxRow([items], false)
			}
		})
	}

	// 全选
	const selectAllChangeEvent1: VxeTableEvents.CheckboxAll = ({checked}) => {
		tableData.value.forEach((items: any) => {
			// 兼容事件
			items.checked = checked
			items.row = {id: items.id}
			selectChangeEvent1(items)
			items.billDetailDTOList.forEach((items2: any) => {
				if (!items2.disableInvoice && items2.invoiceMoney > 0) {
					items2.isDealWith = checked
				}
			})
		})
	}

	const checkInvoice = () => {
		// 租客 包租子合同
		let params = {deptIds: [props.dataDept.deptId]}

		// 包租详情
		if (props.dataSource.contractType === 2 && props.dataSource.houseRoomDTOList?.length) {
			params.deptIds = []
			props.dataSource.houseRoomDTOList?.forEach(e => {
				params.deptIds.push(e.deptId)
			})
		}

		invoicing.verify(params).then(res => {
			pageStatusValue.value = res.data.type
			if (res.data.type == 0) {
				getFinance()
			} else {
				pageStatus[pageStatusValue.value].name = res.data.deptName
			}
		})
	}

	/** 获取账单信息 */
	const getFinance = () => {
		let type = props.dataSource.enterType || 1
		// type 1租客合同or房间维度 2包租合同详情维度
		console.log('props', props)
		// bizId enterContractId feeDirection：1

		console.log('searchParams===', searchParams)

		let params: any = {feeDirection: 1}
		if (type == 1) {
			params.bizId = props.dataSource.id
		}
		if (type == 2) {
			params.enterContractId = props.dataSource.id

			Object.assign(params, searchParams)
		}

		loadings.detail = true
		invoicing.getFinance(params).then(res => {
			tableData.value = res.data

			let ids: any = []
			res.data.forEach(e => {
				e.billDetailDTOList.forEach(j => {
					ids.push(j.id)
				})
			})

			getDetails(ids)
		})
	}

	/** 获取账单明细可开票金额 */
	const getDetails = (ids: any) => {
		invoicing
			.getInvoiceAmount({billDetailIds: ids})
			.then(res => {
				console.log('🚀 ~ file: invoiceing.vue:286 ~ invoicing.getFinance ~ res:', res)
				res.data.forEach(e => {
					tableData.value.forEach(j => {
						j.billDetailDTOList.forEach(k => {
							if (e.billDetailId === k.id) {
								k.hasInvoicingMoney = e.hasInvoicingMoney
								k.invoiceMoney = e.invoiceMoney
								k.disableInvoice = e.disableInvoice
							}
						})
					})
				})
			})
			.finally(() => {
				loadings.detail = false
			})
	}

	/** 获取决策中的发票设置 */
	const getDecision = () => {
		let params = {
			bizPoint: 'INVOICEING_PMS_SETTING',
			module: 'INVOICE'
		}
		settingApi.getDecisionList(params).then(res => {
			if (res.data && res.data.length > 0) {
				console.log('🚀 ~ file: invoiceing.vue:523 ~ settingApi.getDecisionList ~ res.data:', res.data)
				res.data.forEach(item => {
					if (item.mark === 'INVOICEING_DETAIL_RANGE') {
						setting.value = item.onOff === '1'
					}
				})
			}
		})
	}

	/** 开票记录 */
	const record = (id: string) => {
		recordId.value = id
		visibles.records = true
	}

	const onTabChange = () => {
		switch (activeTab.value) {
			case '1':
				getFinance()
				return
			default:
				return
		}
	}

	onMounted(() => {
		console.log('props', props.dataDept)
		checkInvoice()

		// 获取决策中的发票设置
		getDecision()
	})
</script>

<style lang="less">
	.invoice-tabs {
		&.ant-tabs {
			height: 100%;

			.ant-tabs-nav {
				margin-bottom: 0;
			}

			.ant-tabs-content-holder {
				flex: 1;
			}

			.ant-tabs-content-top {
				height: 100%;
			}
		}

		.ant-tabs-extra-content {
			flex: 1;
		}

		.default-box {
			height: 100%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}
	}
</style>
